﻿package 
{
	import flash.display.*;
	import Base64Encoder;
	import flash.net.*;
	import flash.events.*;
	import flash.text.*;
	import flash.utils.*;
	import fl.data.DataProvider;
	import flash.geom.Point;
	import flash.system.Capabilities;
	import flash.geom.Rectangle;
	import flash.desktop.NativeApplication;
	import fl.controls.Button

	public class Main extends MovieClip
	{
		public static var application:MovieClip;
		public static var textbox:MovieClip;
		public static var Timers:Array;

		public static var AddTimer:Button;
		public static var LoadBtn:Button;

		public static var ShowTasks:MovieClip;
		public static var GlobalTimer:Timer;
		public static var ActiveTimer:Number;
		public static var TimerHolder:MovieClip;
		public static var select_task:MovieClip;
		public static var tasks:DataProvider;
		public static var statuses:DataProvider;
		public static var people:DataProvider;
		private static var Background:MovieClip;
		private static var settings:MovieClip;
		public static var todo:NativeApplication;
		
		private static var Total:TextField;
		
		private static var time_to_log:Number;

		public static var index_of_removed:Number;
		public static var index_of_selected:Number;
		public static var Indicator:MovieClip;
		
		private static var old_window_height:int;
		private static var old_window_x:int;
		private static var old_window_y:int;
		private static var fucking_window;

		private static var timer_count:Number;

		public function Main()
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;

			application = Application;
			Indicator = application.indicator;
			Indicator.gotoAndStop(2);
			
			textbox = new text_mc();

			AddTimer = new Button();
			LoadBtn = new Button();

			//ShowTasks = new AddTimerButton();
			GlobalTimer = new Timer(1000);
			TimerHolder = new TimerHolderMC();
			Timers = new Array();
			ActiveTimer = new Number();
			timer_count = 0;
			tasks = new DataProvider();
			people = new DataProvider();
			statuses = new DataProvider();
			Background = application.BG;
			settings = new Settings_mc();
			Total = total;
			time_to_log = 30;
			
			GlobalTimer.start();
			GlobalTimer.addEventListener(TimerEvent.TIMER, onTimer);

			application.addChild(AddTimer);
			AddTimer.addEventListener(MouseEvent.CLICK, _make_new_timer);
			AddTimer.label = 'New Timer';
			AddTimer.x = 10;
			AddTimer.y = 20;
			AddTimer.width = 75;
			AddTimer.mouseChildren = false;
			AddTimer.useHandCursor = true

			application.addChild(LoadBtn);
			LoadBtn.x = 90;
			LoadBtn.y = 20;
			LoadBtn.width = 155;
			LoadBtn.addEventListener(MouseEvent.CLICK, load_timers);
			LoadBtn.label = 'Load/Restore previous timers';
			LoadBtn.mouseChildren = false;
			LoadBtn.useHandCursor = true

			application.addChild(TimerHolder);
			TimerHolder.x = 10;
			TimerHolder.y = 52;

			//this.stage.addChild(ShowTasks);
			//ShowTasks.x = ShowTasks.width;
			//ShowTasks.y = this.stage.stageHeight;
			//ShowTasks.addEventListener(MouseEvent.CLICK, get_tasks);
			application.minimiseButton.addEventListener(MouseEvent.CLICK, minimize_CLICK);
			application.closeButton.addEventListener(MouseEvent.CLICK, close_CLICK);
			application.minimiseButton.buttonMode = true;
			application.closeButton.buttonMode = true;
			//stage.addEventListener(KeyboardEvent.KEY_UP, keyPressHandler);
			
			application.settingsButton.buttonMode = true;
			application.settingsButton.addEventListener(MouseEvent.CLICK, showSettings);
			
			application.DragBar.addEventListener(MouseEvent.MOUSE_DOWN, stage_start_drag);

			stage.nativeWindow.alwaysInFront = false;// window always on top
			fucking_window = stage.nativeWindow;
			
			new_timer('fake');
			
			shrink_stage();
			shrink_stage();
			shrink_stage();
			shrink_stage();
			shrink_stage();
			shrink_stage();
			shrink_stage();
			
			//Logger.loadLogs(new Date());

			//Load today's timers if there are any
			var logs:TimerLog = new TimerLog();
			logs.loadTimers();

			new FirstRun();
			
			Intervals.get_people();
			Intervals.get_statuses();
			//Intervals.get_clients();
			//Intervals.get_modules();
			stage.nativeWindow.minSize = new Point(490,20);
			stage.addEventListener(Event.ACTIVATE, flashActive);
			stage.addEventListener(Event.DEACTIVATE, flashDeactive);
		}

		private function flashActive (e:Event):void
		{
			// if(ActiveTimer)
			// {
			// 	e.target.nativeWindow.height = old_window_height;
			// 	e.target.nativeWindow.width = 601;
			// 	e.target.nativeWindow.y = old_window_x;
			// 	e.target.nativeWindow.x = old_window_y;
			// 	application.alpha = 1;
			// 	application.gotoAndStop(1);
			// 	application.x = 0;
			// 	application.y = 0;
			// 	e.target.nativeWindow.alwaysInFront = false;
			// }
		}
				
		private function flashDeactive (e:Event):void
		{
			// if(ActiveTimer)
			// {
			// 	old_window_height = e.target.nativeWindow.height;
			// 	old_window_x = e.target.nativeWindow.x;
			// 	old_window_y = e.target.nativeWindow.y;
			// 	e.target.nativeWindow.height = 20;
			// 	e.target.nativeWindow.width = 490;
			// 	e.target.nativeWindow.y = 0;
			// 	e.target.nativeWindow.x = (Capabilities.screenResolutionX - e.target.stageWidth) / 2;
			// 	application.alpha = .5;
			// 	application.gotoAndStop(2);
			// 	application.x = -40;
			// 	application.y = Timers[ActiveTimer].y*-1-TimerHolder.y;
			// 	e.target.nativeWindow.alwaysInFront = true;
			// }
		}
		
		private function stage_start_drag(e:MouseEvent)
		{
			stage.nativeWindow.startMove();
		}

		private function load_timers(e:MouseEvent):void
		{
			var options:NativeWindowInitOptions = new NativeWindowInitOptions();
			options.systemChrome = NativeWindowSystemChrome.NONE;
			options.type = NativeWindowType.LIGHTWEIGHT;
			options.transparent = true;
			options.maximizable = false;
			options.resizable = false;
			
			//todo = new NativeApplication();
			
			var win:NativeWindow = new NativeWindow(options);
			win.width = 601;
			win.height = 397;
			win.stage.scaleMode = "noScale";
			win.stage.align = StageAlign.TOP_LEFT;
			win.alwaysInFront = true;

			timerSelect = new TimerSelect();
			
			win.stage.addChild(timerSelect);
			win.x = (Capabilities.screenResolutionX - win.width) / 2;
			win.y = (Capabilities.screenResolutionY - win.height) / 2;		
			win.activate();
		}

		private function _make_new_timer(e)
		{
			new_timer();
		}
		
		public static function new_timer(timer_id=false, task_time=null, task_number=null, description=null)
		{
			if(!timer_id)
			{
				var timerLog:TimerLog = new TimerLog();
				timerLog.date = new Date();
				timer_id = timerLog.insert();
			}
			else if(timer_id=='fake')
			{
				timer_id=false;
			}
			
			var task_timer:MovieClip = new TaskTimer(timer_id);

			TimerHolder.addChild(task_timer);
			task_timer.y = 30 * timer_count-30;
			task_timer.x = 10;
			task_timer.set_index(Timers.length);
			if(task_time)
			{
				task_timer.update_time(task_time);
			}
			if(description || task_number)
			{
				var task = new Object();
				task.localid = task_number;
				task.title = description;
				task_timer.set_task(task, false);
			}
			//task_timer.task_name.open_tasks.addEventListener(MouseEvent.CLICK, show_task_list);
			Timers[Timers.length] = task_timer;
			timer_count++;
			if(timer_count==1)
			{
				//Timers[0].alpha = 0;
				Timers[0].y = -100;
			}
			if (timer_count > 2)
			{
				grow_stage();
			}
		}

		private static function grow_stage()
		{
			Background.height += 30;
			fucking_window.height += 30;
			TimerHolder.TimerHolderBg.height += 30;
		}

		private static function shrink_stage()
		{
			Background.height -= 30;
			fucking_window.height -= 30;
			TimerHolder.TimerHolderBg.height -= 30;
		}

		public static function update_tasks(xml:XML)
		{
			tasks.removeAll();
			var task_list=xml.task;
			for each(var task in xml.task.*)
			{
				var taskObj:Tasks = new Tasks();
				taskObj.set_details(task);

				tasks.addItem(taskObj); // , task_number:tasks.task.item.localid[i].text()});
			}
			Indicator.gotoAndStop(2);
		}

		public static function update_people(xml:XML)
		{
			people.removeAll();
			var i:Number;
			for (i=0; i<xml.person.item.length(); i++)
			{
				var current_label:String;
				current_label=xml.person.item.firstname[i].text()+" "+xml.person.item.lastname[i].text();

				people.addItem({label:current_label, id:xml.person.item.id[i].text()});
			}
			Indicator.gotoAndStop(2);
		}

		public static function update_statuses(xml:XML)
		{
			statuses.removeAll();
			var i:Number;
			for (i=0; i<xml.taskstatus.item.length(); i++)
			{
				var current_label:String;
				current_label=xml.taskstatus.item.name[i].text();

				statuses.addItem({label:current_label, id:xml.taskstatus.item.id[i].text()});
			}
			Indicator.gotoAndStop(2);
		}

		private function onTimer(e)
		{
			var current_time=getTimer();
			stage.nativeWindow.title = '';
			if(ActiveTimer)
			{
				Timers[ActiveTimer].set_time(current_time-Timers[ActiveTimer].get_start_time());
				var task = '';
				if(Timers[ActiveTimer].get_task_number())
				{
					task += '#'+Timers[ActiveTimer].get_task_number()+' ';
				}
				task += Timers[ActiveTimer].get_timer_description();
				if(task!='')
				{
					task = ' ' + task;
				}
				stage.nativeWindow.title = Tools.formatTime(current_time-Timers[ActiveTimer].get_start_time())+task+' | ';
				// calculate total time
				var total_time:uint = 0;
				for each (var i in Timers)
				{
					total_time += i.get_time();
				}
				Total.text = Tools.formatTime(total_time);
				
				if(time_to_log<0)
				{
					Timers[ActiveTimer].log_me();
					time_to_log = 30;
				}
				else
				{
					time_to_log--;
				}
			}
			stage.nativeWindow.title += 'Total: '+Total.text;
		}

		public static function timer_deleted(e)
		{
			if (e.target is TaskTimer)
			{
				timer_count--;
				for (var i=0; i<Timers.length; i++)
				{
					if (i>index_of_removed)
					{
						if (Timers[i])
						{
							Timers[i].y-=30;
						}
					}
				}
				if(timer_count>=2)
				{
					shrink_stage();
				}
			};
			index_of_removed=NaN;
		}

		public static function recieve_xml(_return:Object)
		{
			switch(_return._type)
			{
				case 'tasks':
					update_tasks(_return._xml);
					break;
				case 'people':
					update_people(_return._xml);
					break
				case 'statuses':
					update_statuses(_return._xml);
					break
			}
		}
	
		function minimize_CLICK(e:MouseEvent):void
		{
			stage.nativeWindow.minimize();
		}
	
		function close_CLICK(e:MouseEvent):void
		{
			try
			{
				var timerLog:TimerLog = new TimerLog();
				timerLog.cleanup();
				for each (var t in Timers)
				{
					t.log_me();
				}
				for ( var i:int = NativeApplication.nativeApplication.openedWindows.length - 1; i >= 0; --i ) {
					NativeWindow( NativeApplication.nativeApplication.openedWindows[i] ).close();
				}
			}
			catch(e)
			{
				new Errors(e);
			}
		}
		
//		function keyPressHandler(e:KeyboardEvent)
//		{
//			trace('key '+e.keyCode);
//			if(e.keyCode==78) // n
//			{
//				_make_new_timer(MouseEvent);
//			}
//		}
		
		public function showSettings(e:MouseEvent):void
		{
			var options:NativeWindowInitOptions = new NativeWindowInitOptions();
			options.systemChrome = NativeWindowSystemChrome.NONE;
			options.type = NativeWindowType.LIGHTWEIGHT;
			options.transparent = true;
			options.maximizable = false;
			options.resizable = false;
			
			//todo = new NativeApplication();
			
			var win:NativeWindow = new NativeWindow(options);
			win.width = 421;
			win.height = 136;
			win.stage.scaleMode = "noScale";
			win.stage.align = StageAlign.TOP_LEFT;
			win.alwaysInFront = true;
			
			settings = new Settings_mc();
			
			win.stage.addChild(settings);
			win.x = (Capabilities.screenResolutionX - win.width) / 2;
			win.y = (Capabilities.screenResolutionY - win.height) / 2;		
			win.activate();
		}
		
		public static function set_preference(pref_name, pref_value)
		{
			trace(pref_name);
			switch(pref_name)
			{
				case 'user_id':
					Settings.user_id = pref_value;
				break;
				
				case 'api_key':
					Settings.api_key = pref_value;
				break;
			}
		}
		
		public function get_data_providers()
		{
			var dps:Object = new Object();
			dps.people = people;
			dps.tasks = tasks;
			dps.statuses = statuses;
			return dps;
		}
		
		public static function set_index_of_selected(index)
		{
			index_of_selected = index;
		}
		
		public function set_task(task:Object)
		{
			Timers[index_of_selected].set_task(task);
		}
	}
}